package com.lspopi.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class TempleteRenderTimeInterceptop extends HandlerInterceptorAdapter {
	private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("StopWatch-StartTime");
	private static final Logger logger = LoggerFactory.getLogger(TempleteRenderTimeInterceptop.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String uri = request.getRequestURI();
		String ctxPath = request.getServletContext().getContextPath();
		uri = uri.replaceAll(ctxPath, "");
		if (!(uri.startsWith("/js") || uri.startsWith("/css") || uri.startsWith("/img") || uri.startsWith("/skins"))) {
			long beginTime = System.currentTimeMillis();// 1、开始时间
			startTimeThreadLocal.set(beginTime);// 线程绑定变量（该数据只有当前请求的线程可见）
			logger.debug(String.format("%s consume ", uri));
		}

		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		String uri = request.getRequestURI();
		String ctxPath = request.getServletContext().getContextPath();
		uri = uri.replaceAll(ctxPath, "");
		if (!(uri.startsWith("/js") || uri.startsWith("/css") || uri.startsWith("/img") || uri.startsWith("/skins"))) {
			long endTime = System.currentTimeMillis();// 2、结束时间
			long beginTime = startTimeThreadLocal.get();// 得到线程绑定的局部变量（开始时间）
			long consumeTime = endTime - beginTime;// 3、消耗的时间
			// request.setAttribute("consume", consumeTime);
			logger.debug(String.format("%s consume %s millis", uri, consumeTime));
			request.setAttribute("consume", consumeTime);
		}

	}
}
